<template>
	<view class="main">
		<van-form class="form-box">
			<van-cell-group inset>
				<view class="form-title">
					<van-field v-model="form.title" required label="会议标题：" placeholder="请输入会议标题" label-align="top" :rules="[{ required: true }]" />
				</view>
			</van-cell-group>
			<van-cell-group inset style="margin-top: 10px;">
				<view>
					<van-field v-model="form.deptName" required readonly label="承办部门":rules="[{ required: true }]" />
					<van-field v-model="form.publishTime" required readonly label="申请日期":rules="[{ required: true }]" />
					<van-field v-model="form.createBy" required readonly label="承办人":rules="[{ required: true }]" />
					<van-field v-model="form.telephone" label="联系电话":rules="[{ required: true }]" />
				</view>
			</van-cell-group>
			<van-cell-group inset style="margin-top: 10px;">
				<view>
					<van-field v-model="form.startTime" required is-link readonly name="datePicker" label="会议开始时间" placeholder="请选择" @click="openPicker(0)" />
					<van-field v-model="form.endTime" required is-link readonly name="datePicker" label="会议结束时间" placeholder="请选择" @click="openPicker(1)" />
					<!-- <van-field v-model="form.meetAddress" required label="会议地点" placeholder="请输入" :rules="[{ required: true }]" /> -->
					<van-field v-model="form.meetAddress" required is-link readonly label="会议室" placeholder="请选择" :rules="[{ required: true }]" @click="openPlace()" />
					<van-field v-model="form.meetLeader" required is-link readonly label="会议主持人" placeholder="请选择" :rules="[{ required: true }]" @click="openSelect(1)" />
					<van-field v-model="form.readerNames" required is-link readonly label="参会人员" placeholder="请选择" :rules="[{ required: true }]" @click="openSelect(2)" />
					<van-field v-model="form.meetNumber" label="参会人数" placeholder="请输入" />
					<van-field v-model="form.meetAttender" label="其他参会人员" placeholder="请输入" />
				</view>
			</van-cell-group>
			<van-cell-group inset style="margin-top: 10px;">
				<view class="form-content">
					<van-field v-model="form.content" label="正文" placeholder="请输入正文" rows="4" label-align="top" autosize type="textarea" />
				</view>
			</van-cell-group>
			<van-cell-group inset style="margin-top: 10px;">
				<view>
					<van-field v-model="form.memo" label="备注" placeholder="请输入备注" />
				</view>
			</van-cell-group>
			<view class="frct">
				<view class="fr-colum">
					<view class="fr-row fr-lable fr-2 fr-2-line">
						<text>附件</text>
						<DhUpload v-if="form.businessId" style="flex: none" upload-type="MEETING" :business-id="form.businessId"  @upload-success="handleFilesSuccess"  :selected-files="fileList">
							<template #trigger="{ selectFile }">
							     <text class="c1">+添加</text>
							  </template>
						</DhUpload>
					</view>
					<view class="fiellist">
						<view class="fr-row flieit" v-for="(file, index) in fileList" :key="index">
							<text class="tname">{{ file.fileName }}</text>
							<text class="tsize">{{ file.fileSize }}</text>
							<uv-icon name="close" color="#2D75D7" size="14" @click="deleteFile(index)"></uv-icon>
						</view>
					</view>
				</view>
			</view>
			<van-cell-group inset style="margin-top: 10px;">
				<view>
					<van-field v-model="form.businessStatus" required label="选择路径"  label-align="top">
						<van-radio-group v-model="form.businessStatus" direction="horizontal" slot="input">
						  <van-radio name="UNDO">送审</van-radio>
						  <van-radio name="DONE">发布通知</van-radio>
						</van-radio-group>
					</van-field>
					<view v-if="form.businessStatus=='UNDO'" style="display: flex;flex-wrap: wrap;">
						<view class="btn-plus" v-for="item, i in personList" :key="i">
							<p>
								<van-button icon="manager" round />
								<text>{{item.name}}</text>
								<image src="/static/docmumentImg/icdelt.png" class="icdelt"
									@click="deletPerson(i, item)"></image>
							</p>
						</view>
						<view class="btn-plus" @click="getPerson()">
							<p>
								<van-button icon="plus" round />
								<text>添加审批人</text>
							</p>
						</view>
					</view>
				</view>
			</van-cell-group> 
			<view class="footer">
				<van-button block color="#2D75D7" plain @click="onSubmit(0)">
					保存
				</van-button>			
				<van-button block color="#2D75D7" @click="onSubmit(1)">
					提交
				</van-button>
			</view>
		</van-form>
		<van-popup v-model:show="showPicker" position="bottom">
			<van-datetime-picker v-model="currentDate" type="datetime" :title="pickerTitle" :min-date="minDate" @confirm="onConfirm" />
		</van-popup>
	</view>
</template>

<script>
import { getRequestUrl } from '@/utils/request.js'
import { auditInfo, auditSave } from '../../../api/meetingNoticeApi'
import { filterNull, parseTime } from '../../../utils/format'
import { getCookie } from '../../../utils/js-cookie'
export default {
	data() {
		return {
			form: {
				meetLeader: '',
				readerNames: '',
				meetAddress: '',
				businessStatus: ''
			},
			showPicker: false,
			minDate: new Date(),
			pickerTitle: '',
			currentDate: '',
			personList: [],
			// 允许的文件类型
			allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'txt'],
			// 单个文件最大大小 (10MB)
			maxSingleSize: 10 * 1024 * 1024,
			// 总文件最大大小 (50MB)
			maxTotalSize: 50 * 1024 * 1024,
			// 文件列表
			fileList: [],
			// 上传中状态
			uploading: false,
			// 当前总大小
			totalSize: 0,
			uploadErrors: []
		}
	},
	onLoad(e) {
		if(e.businessId) {
			this.loadInit(e.businessId)
		} else {
			this.init()
		}
	},
	onShow() {
		this.getPersonInfo()
	},
	methods: {
		getPersonInfo(){
			let personInfo = uni.getStorageSync('selectPsersonData')
			console.log('person', personInfo)
			if(personInfo){
				personInfo = JSON.parse(personInfo)
				this.form.auditorIds = personInfo.ids
				this.form.auditorNames = personInfo.names
				this.form.auditorAccounts = personInfo.mobiles
				console.log('personinfo', personInfo)
				this.personList = personInfo.personList
				uni.removeStorageSync('selectPsersonData')
			}
			
			let single = uni.getStorageSync('singleSelectPsersonData')
			if(single){
				single = JSON.parse(single)
				console.log('single', single)
				this.form.meetLeaderId = single.ids
				this.form.meetLeader = single.names
				uni.removeStorageSync('singleSelectPsersonData')
			}
			
			let multi = uni.getStorageSync('multiSelectPsersonData')
			if(multi){
				multi = JSON.parse(multi)
				console.log('multi', multi)
				this.form.readerIds = multi.ids
				this.form.readerNames = multi.names
				this.form.readerAccounts = personInfo.mobiles
				uni.removeStorageSync('multiSelectPsersonData')
			}
			
			let room = uni.getStorageSync('selectRoomData')
			if(room){
				room = JSON.parse(room)
				console.log('multi', multi)
				this.form.meetAddressId = room.id
				this.form.meetAddress = room.name
				uni.removeStorageSync('selectRoomData')
			}
		},
		init(){
			this.form.publishTime = parseTime(new Date(), '{y}-{m}-{d}')
			const userInfo = JSON.parse(getCookie('userInfo'))
			console.log('userInfo', userInfo)
			this.form.deptId = userInfo.deptId || ''
			this.form.deptName = userInfo.deptName || ''
			this.form.createBy = userInfo.personName
			this.form.createId = userInfo.personId
			this.form.telephone = userInfo.personMobile
			
			auditInfo().then(res=>{
				this.form.businessId = res.data.businessId
				this.form.isNew = true
			})
		},
		loadInit(businessId){
			auditInfo({id: businessId}).then(res=>{
				console.log('res', res)
				Object.assign(this.form, filterNull(res.data))
				this.form.isNew = false
				this.personList = this.form.auditorNames.split(',').map((e, i)=>{
					return {
						name: e
					}
				})
			})
		},
		onSubmit(type){
			console.log('submit', this.form, type)
			if(type==0){
				this.form.operateType = 'draft'
			}else{
				this.form.operateType = 'complete'
			}
			this.form.publishScope = 'DESIGNEE'
			this.form.receiptStatus = 1
			auditSave(this.form).then(res=>{
				console.log('res', res)
				uni.showToast({
					title: '提交成功',
					icon: 'success'
				})
				setTimeout(()=>{
					uni.navigateBack()
				}, 800)
			})
		},
		openPicker(type){
			if(type==0){
				this.pickerTitle = '开始时间'
			}else if(type==1){
				this.pickerTitle = '结束时间'
			}
			this.showPicker = true
		},
		onConfirm(){
			if(this.pickerTitle.includes('开始')){
				this.minDate = this.currentDate
				this.form.startTime = parseTime(this.currentDate, '{y}-{m}-{d} {h}:{i}')
			}else if(this.pickerTitle.includes('结束')){
				this.form.endTime = parseTime(this.currentDate, '{y}-{m}-{d} {h}:{i}')
			}
			this.showPicker = false
		},
		afterRead(){
			
		},
		// 去选择人
		getPerson() {
		    uni.navigateTo({
		        url: `/documentManagement/selectPerson/circulate?title=添加审批人&selected=${this.form.auditorNames}`
		    });
		},
		openPlace(){
			uni.navigateTo({
				url: `/pages/meeting/notice/select?flCreateId=${this.form.createId}`
			})
		},
		openSelect(type){
			uni.navigateTo({
			    url: `/pages/components/select/circulate?type=${type}&selected=${type==1?'':this.form.readerNames}`
			});
		},
		// J计算文件大小
		FileSize() {
			this.totalSize = 0;
			this.totalSize = this.fileList.reduce((sum, file) => {
				return sum + (file.fileRealSize || 0);
			}, 0);
			this.form.busiAttachIds = this.fileList && this.fileList.length > 0 ? this.fileList.map((file) =>
				file.id).join() : null;
		},
		// 上传前文件类型检查
		beforeFileRead(file) {
			this.FileSize();
			const files = Array.isArray(file.file) ? file.file : [file];

			let isValid = true;
			files.forEach((f) => {
				// 检查文件类型
				const ext = this.getFileExtension(f.name || f.url).toLowerCase();
				console.log(files, ext);
				if (!this.allowedExtensions.includes(ext)) {
					uni.showToast({
						title: `不支持的文件类型: ${ext}`,
						icon: 'none'
					});
					isValid = false;
					return;
				}

				// 检查单个文件大小
				if (f.size > this.maxSingleSize) {
					uni.showToast({
						title: '单个文件大小不能超过10MB',
						icon: 'none'
					});
					isValid = false;
					return;
				}

				// 检查总大小
				const newTotalSize = this.totalSize + f.size;
				if (newTotalSize > this.maxTotalSize) {
					uni.showToast({
						title: '文件总大小不能超过50MB',
						icon: 'none'
					});
					isValid = false;
				}
			});
			return isValid;
		},
		// 获取文件扩展名
		getFileExtension(filename) {
			if (!filename) return '';
			return filename.split('.').pop().toLowerCase();
		},
		// 文件上传成功的返回
		handleFilesSuccess(files) {
			if (!Array.isArray(files)) {
				files = [files]; // 如果不是数组，转为数组
			}
			const newResponses = files
				.filter(file => file?.response) // 过滤掉没有response的项
				.map(file => file.response);   // 提取response
			this.fileList = [...this.fileList, ...newResponses];
			this.form.busiAttachIds = this.fileList && this.fileList.length > 0 ? this.fileList.map((file) =>file.id).join() : null;
			console.log('更新后的文件列表', this.fileList);
		},
		// 删除文件
		deleteFile(index) {
			this.fileList.splice(index, 1);
			this.FileSize()
		},
		// 处理文件上传后逻辑
		async afterRead(event) {
			const files = Array.isArray(event.file) ? event.file : [event.file];
			this.uploading = true;
			this.uploadErrors = [];
			try {
				// 并行处理所有文件上传，但按顺序收集结果
				const results = await Promise.allSettled(files.map((file, index) => this.uploadFilePromise(file
					.url, index)));
				// 处理成功的上传结果
				results.forEach((result, index) => {
					if (result.status === 'fulfilled') {
						if (result.value) {
							this.fileList.push(result.value);
							this.FileSize();
						}
					} else {
						this.uploadErrors.push({
							index,
							error: result.reason
						});
					}
				});

				if (this.uploadErrors.length > 0) {
					uni.showToast({
						title: `部分文件上传失败(${this.uploadErrors.length}/${files.length})`,
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: '全部文件上传成功',
						icon: 'none',
						duration: 1500
					});
				}
			} catch (error) {
				console.error('文件上传过程中发生错误:', error);
				uni.showToast({
					title: '上传过程中发生错误',
					icon: 'none'
				});
			} finally {
				this.uploading = false;
			}
		},
		uploadFilePromise(url, fileIndex) {
			return new Promise((resolve, reject) => {
				const base_url = uni.getStorageSync('apiUrl') ? uni.getStorageSync('apiUrl') : '/api';
				uni.uploadFile({
					url: getRequestUrl() + '/app/workflow/business_attach/upload/MEETING/' + this.form.businessId,
					filePath: url,
					name: 'files',
					header: {
						'ECWEB-JWTSSO-TOKEN': uni.getStorageSync('token')
					},
					success: (res) => {
						try {
							// 直接解析响应数据
							const responseData = JSON.parse(res.data);
							if (responseData && responseData.data && responseData.data[0]) {
								resolve(responseData.data[0]);
							} else {
								reject(new Error('服务器返回数据格式错误'));
							}
						} catch (parseError) {
							reject(parseError);
						}
					},
					fail: (err) => {
						reject(err);
					}
				});
			});
		},
		deletPerson(index, name) {
			// 从数组中移除指定索引的审批人
			this.personList.splice(index, 1);
			// 更新 form 中的审批人信息
			const ids = this.form.auditorIds ? this.form.auditorIds.split(',') : [];
			const names = this.form.auditorNames ? this.form.auditorNames.split(',') : [];
			ids.splice(index, 1);
			names.splice(index, 1);
			this.form.auditorIds = ids.join(',');
			this.form.auditorNames = names.join(',');
		},
	}
}
</script>

<style lang="scss" scoped>
.main {
	background-color: #f5f5f5;
	min-height: 100vh;
}
.form-box{
	position: relative;
	top: 0;
	left: 0;
	width: 100%;
	padding-top: 10px;
	margin-bottom: 50rpx;
	border-bottom: 0;
	min-height: 0;
	padding-bottom: 77px;
}
.form-title{
	::v-deep .van-cell{
		flex-direction: column;
	}
	::v-deep .van-field__body{
		border-bottom: 1px solid #efefef;
		margin-top: 10px;
	}
}
.form-content{
	::v-deep .van-cell{
		flex-direction: column;
	}
	::v-deep .van-field__body{
		border: 1px solid #efefef;
		margin-top: 10px;
		padding: 5px;
	}
}
.footer{
	position: fixed;
	bottom: 0;
	background-color: #fff;
	width: 95%;
	padding: 10px;
	display: flex;
	justify-content: space-between;
	::v-deep .van-button--block{
		width: 48%;
	}
}
.uploader{
	width: 100%;
	::v-deep .van-uploader__input-wrapper{
		width: 100%;
	}
}
.btn-plus{
	display: flex;
	padding: 10px;
	p {
		display: flex;
		flex-direction: column;
		align-items: center;
		text{
			font-size: 14px;
			color: #999999;
			margin-top: 5px;
		}
	}
}

.frct {
    margin: 16px;
    margin-bottom: 0;
    padding: 16px;
    font-size: 16px;
    background: #fff;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
	.fr-colum {
	    display: flex;
	    flex-direction: column;
	    position: relative;
	}
	.fr-2 {
	    color: #a5a5a5;
	    font-weight: 400;
	}
	.fr-lable {
	    color: #555555;
	    padding-bottom: 11px;
	    font-weight: bold;
	}
	.fr-row {
	    display: flex;
	    flex-direction: row;
	    justify-content: space-between;
	    align-items: center;
	}
	.fiellist {
	    padding: 14px 0;
	    border-top: 1px solid #efefef;
	}
}

::v-deep .uv-upload__wrap__preview {
	display: none;
}

.icdelt{
    position: relative;
    width: 20px;
    height: 20px;
    top: -80%;
    right: -40%;
}
</style>